import type { IconfontPageTypeResult } from './types'
import { getCurrentSearch } from '../../../../types/constants'
import { PageRoute } from '../../../abstract/page_route'
import { IconfontPageType } from './types'

export class IconfontPage extends PageRoute {
  readonly name: string = 'IconfontPage'
  private static instance: IconfontPage
  get pageType(): IconfontPageType | 'default' {
    return this.getCurrentPageMeta().type
  }

  /**
   * 获取单例实例
   */
  public static getInstance(): IconfontPage {
    if (!IconfontPage.instance) {
      IconfontPage.instance = new IconfontPage()
    }
    return IconfontPage.instance
  }

  /**
   * 获取当前页面类型
   */
  public getCurrentPageMeta(): IconfontPageTypeResult {
    const url = this.getCurrentUrl()
    const path = new URL(url).pathname

    // 404 页面检测
    const notFoundResult = this.detectNotFoundPage()
    if (notFoundResult)
      return notFoundResult

    // 基础页面检测
    const pageResult = this.detectPages(path)
    if (pageResult)
      return pageResult

    // 未定义页面
    return { type: IconfontPageType.Undefined }
  }

  /**
   * 检测 404 页面
   */
  private detectNotFoundPage(): IconfontPageTypeResult | null {
    const pageNotFoundRules = [
      /404.*Not Found/i, // 不区分大小写
    ]

    if (pageNotFoundRules.some(regex => regex.test(document.title))) {
      return { type: IconfontPageType.NotFound }
    }

    return null
  }

  /**
   * 检测其他功能页面
   */
  private detectPages(basePath: string): IconfontPageTypeResult | null {
    const pageDetectors: Array<[RegExp, (...args: any[]) => IconfontPageTypeResult]> = [
      // 首页
      [/^\/$/, () => {
        return { type: IconfontPageType.Index }
      }],
      // 搜索
      [/^\/search\/index\/?$/, () => {
        return this.detectSearchType()
      }],
      // 搜索
      [/^\/collections\/detail\/?$/, () => {
        return { type: IconfontPageType.CollectionsDetail }
      }],
    ]

    for (const [regex, handler] of pageDetectors) {
      const match = basePath.match(regex)

      if (match) {
        return handler(match)
      }
    }

    return null
  }

  /**
   * 检测搜索类型（图标搜索或插画搜索）
   */
  private detectSearchType(): IconfontPageTypeResult {
    const urlParams = new URLSearchParams(getCurrentSearch())
    const typeParam = urlParams.get('searchType')

    if (typeParam === 'illustration') {
      return { type: IconfontPageType.SearchIllustration }
    }
    else if (typeParam === 'icon') {
      return { type: IconfontPageType.SearchIcon }
    }
    else {
      return { type: IconfontPageType.SearchIcon }
    }
  }
}
